<template>
  <div class="app-container">
    <!-- 表格-条件筛区域  -->
    <div class="filter-container">
        <el-input placeholder="请输入申请人姓名" v-model="searchParam.SEARCH_EQ_real_name" clearable style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
        <el-input placeholder="请输入申请人电话" v-model="searchParam.SEARCH_EQ_mobile" clearable style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
        <el-input placeholder="请输入申请人邮箱" v-model="searchParam.SEARCH_EQ_email" clearable style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-select placeholder="请选择申请状态" v-model="searchParam.SEARCH_EQ_apply_status" clearable style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter">
          <el-option value=0 label="待申请" ></el-option>
          <el-option value=1 label="待审核" ></el-option>
          <el-option value=2 label="通过" ></el-option>
          <el-option value=3 label="拒绝" ></el-option>
      </el-select>
      <el-date-picker
          class="filter-item"
          v-model="dateRange"
          type="datetimerange"
          align="right"
          unlink-panels
          value-format="yyyy-MM-dd HH:mm:ss"
          range-separator="/"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="handleSelect"
          :default-time="['00:00:00', '23:59:59']"
      >
      </el-date-picker>


      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter"> 搜索 </el-button>
      <el-button class="filter-item" type="primary" :disabled="multipleSelection.length<1" :loading="uploadNoSignet"
                 icon="el-icon-search" @click="certNoSignet"> 无章发放（批量） </el-button>
        <el-button class="filter-item" type="primary" :disabled="multipleSelection.length<1"
                   icon="el-icon-search" @click="downSignet"> (批量）下载 </el-button>
    </div>

    <!-- 表格-内容区域 -->
    <el-table v-loading="listLoading" :key="tableKey" :data="tableList" border fit highlight-current-row style="width: 100%;"
              @selection-change="handleSelectionChange" ref="multipleTable"
    >
        <el-table-column
            type="selection"
            width="55">
        </el-table-column>
      <el-table-column v-for="column in columns" :key="column.prop"
                       :prop="column.prop"
                       :label="column.label"
                       :width="column.width"
                       :align="column.align?column.align:'center'"
                       :min-width="column.minWidth"
                       :sortable="column.sortable"
                       :fixed="column.fixed"
                       :type="column.type" :formatter="column.formatter">
        <template slot-scope="scope">
          <!-- 行内显示图片 -->
            <img @click="clickImg(scope.row[column.prop])" v-if="column.imgFlag==true && scope.row[column.prop]" :src=" scope.row[column.prop].indexOf('http') >-1 ?  scope.row[column.prop] : ( CMBASE.baseFileContext + scope.row[column.prop] ) " width="60" height="60" class="img"/>
          <!-- 行内显示开关按钮 -->
          <el-switch v-else-if="column.switchFlag==true" v-model="scope.row[column.prop]" :active-value="1" :inactive-value="0"  disabled />
          <!-- 行内显示tag标签 -->
          <span  v-else-if="column.tagFlag==true">
                        <span v-for="item in column.tagFormatter" :key="item.value" >
                            <el-tag v-if="item.value==scope.row[column.prop]"   :type="item.type">{{item.text}}</el-tag>
                        </span>
                    </span>
          <!-- 行内格式自定义 -->
          <span v-else-if="column.formatter"> {{column.formatter(scope.row)}}</span>
          <!--默认显示文本-->
          <span v-else>{{scope.row[column.prop]}}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="240" class-name="small-padding">
        <template slot-scope="scope">
<!--          <el-button type="text"  icon="el-icon-download" class="el-button&#45;&#45;primary" v-if="scope.row.certImgNoSignet"  :loading="buttonLoading"  @click="uploadWithoutSeal(scope.row)">下载(无章版)</el-button>-->
          <el-button type="text"  icon="el-icon-plus" class="el-button--primary"   @click="handleInfo(scope.row)"> 详情</el-button>
          <el-button type="text"  icon="el-icon-bottom" class="el-button--primary"   @click="handleResult(scope.row)"> 重发</el-button>
          <el-button type="text"  icon="el-icon-check" class="el-button--primary" v-if="scope.row.applyStatus===1"  @click="handlePass(scope.row)"> 通过</el-button>
          <el-button type="text"  icon="el-icon-close" class="el-button--primary" v-if="scope.row.applyStatus===1"  @click="handleNoPass(scope.row)"> 拒绝</el-button>
<!--          <el-button type="text"  icon="el-icon-edit" class="el-button&#45;&#45;primary"   @click="showDialog=true"> 详情</el-button>-->
<!--          <el-button type="text"  icon="el-icon-edit" class="el-button&#45;&#45;primary" v-if="scope.row.applyStatus===1"  @click="handleUpdate(scope.row)"> 审核</el-button>-->
<!--          <el-button type="text"  icon="el-icon-delete"   class="el-button&#45;&#45;danger"  @click="handleDelete(scope.row)"> 删除 </el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <!-- 表格-页脚区域 -->
    <pagination v-show="tableTotal>0" :total="tableTotal" :page.sync="pageRequest.pageNum" :limit.sync="pageRequest.pageSize" @pagination="getList"/>

    <!--新增编辑界面-->
    <el-dialog :title="operation?'新增':'编辑'" width="45%" top="5vh" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      <el-form :model="dataForm" label-width="140px" :rules="dataFormRules" ref="dataForm" style="width: 80%">

        <el-form-item label="申请状态" prop="applyStatus">
<!--          <el-input v-model="dataForm.applyStatus" auto-complete="off" placeholder="请输入申请状态 0待申请 1待审核 2已通过 3已拒绝"/>-->
          <el-select v-model="dataForm.applyStatus">
            <el-option :value="2" :label="'通过'" ></el-option>
            <el-option :value="3" :label="'拒绝'" ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click.native="closeDialog()">取消</el-button>
        <el-button size="mini" @click.native="saveFormData()" :loading="editLoading" type="primary">提交 </el-button>
      </div>
    </el-dialog>

    <el-dialog title="申请详情" :visible.sync="showDialog" width="65%" top="5vh" :close-on-click-modal="false"  >

      <div class="filter-container">
        <el-radio-group v-model="type" class="filter-item" @change="handleInfo(dataForm)" >
          <el-radio :label="1">考试</el-radio>
          <el-radio :label="2">课程</el-radio>
        </el-radio-group>
      </div>

      <cert-exam-list v-if="showDialog" :table-list="itemDataForm" :num="type" ></cert-exam-list>

    </el-dialog>

      <el-dialog :visible.sync="clickImgDialog" top="5vh" append-to-body>
          <div style="text-align:center;display:flex" >
              <img style="width:100%" :src="dialogImageUrl" alt="" v-if="clickImgDialog">
          </div>
      </el-dialog>


  </div>
</template>
<script>
import Pagination from '@/components/Pagination'
import CertExamList from "./certExamList.vue";  // 分页栏信息
export default {
  name: 'user_cert',
  components: {
    Pagination,
    CertExamList,

  },
  directives: {   },
  filters: { },
  data() {
    return {
      tableKey: 0,
      itemKey: 0,
      tableList: [],//表格数据源
      tableTotal: 0,//表格总条数数据
      listLoading: true,
      dialogImageUrl:'',
      type:1,
      id:'',
      pageRequest: { pageNum: 1, pageSize: 10, },
      searchParam:{},
      orderParam:{ apply_status: true,create_time:false },
      dialogFormVisible: false,//默认不显示弹出框
      uploadNoSignet: false,//默认不显示弹出框
      operation: true, // true:新增, false:编辑
      editLoading: false,//保存表单时loading框
      showDialog: false,//保存表单时loading框
      dialogLoading: false,//保存表单时loading框
      clickImgDialog: false,//保存表单时loading框
      buttonLoading: false,//保存表单时loading框
      columns: [
        {prop: 'realName',  label: '用户姓名',  sortable:false  },
        {prop: 'mobile',  label: '用户手机',  sortable:false  },
        {prop: 'applyStatus',  label: '申请状态',  sortable:false ,  tagFlag: true, width: 100,
          tagFormatter: [
            { text: '待申请', value: 0, type: 'success' },
            { text: '待审核', value: 1, type: 'success' },
            { text: '已通过', value: 2, type: 'warn' },
            { text: '已拒绝', value: 3, type: 'warn' },
          ]
        },
        {prop: 'createTime',  label: '申请时间',  sortable:false  },
        {prop: 'certPath',  label: '证书地址',  sortable:false, imgFlag: true },
        {prop: 'certImg',  label: '证书图片',  sortable:false , imgFlag:true },
        {prop:'certImgNoSignet' ,label:'证书图片（无章）' ,sortable:false, imgFlag: true},
        {prop: 'certName',  label: '证书名称',  sortable:false  },
        {prop: 'certNumber',  label: '证书编号',  sortable:false  },
        {prop: 'remark',  label: '审核备注',  sortable:false  },

      ],
      fileList: [],
      // 新增编辑界面数据
      dataForm: {},
      itemDataForm: [],//表格数据源
      itemRuleForm: {},//表格数据源
      dateRange:'',
      //表单检验规则
      dataFormRules: {
      },
      //列表多选
      multipleSelection: []
    }
  },
  created() {
    this.getList();
  },
  methods: {
     certNoSignet(){
         this.uploadNoSignet = true
      this.$api.certNoSignet({ids:this.multipleSelection.join(",")}).then(item=>{
          this.uploadNoSignet = false
          this.getList();
      }).catch(err=>{
          this.$notify.error({
              title: '操作失败',
              message: err.message,
          });
          this.uploadNoSignet = false
      })
     },
     downSignet(){
         try{
             const ids = this.multipleSelection.join(",")
             window.open(this.CMBASE.baseFileContext+"/CM-API/CUserCert/downloadZip?ids="+ids)
             // window.open("http://127.0.0.1:4009"+"/CM-API/CUserCert/downloadZip?ids="+ids)
         }catch (e) {
             this.$notify.error({
                 title: '下载失败',
                 message: '无法下载文件，请稍后重试'
             });
         }
     },
    //获取表格数据
    getList() {
      this.listLoading = true
      //【API请求】----获取表格列表数据
      this.pageRequest.orderParam = this.orderParam
      this.pageRequest.searchParam = this.searchParam
      this.$api.getCUserCertList(this.pageRequest).then(response => {
        this.tableList = response.data.content
        this.tableTotal = response.data.total
        this.listLoading = false;
      }).catch((res) => {
        this.$message({  message: '列表获取失败', type: 'error' })
      })
    },
    //表格数据筛选
    handleFilter() {
      this.pageRequest = {
          pageNum: 1,
          pageSize: 10,
      }
      this.pageRequest.searchParam = this.searchParam
      this.getList()
    },
    //【按钮点击】--- 弹出新增表单
    handleCreate() {
      this.operation = true;
      this.initDataForm();
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        this.editLoading = false;
      })
    },
    //【按钮点击】--- 弹出编辑表单
    handleUpdate(row) {
      this.operation = false;
      this.dataForm = Object.assign({}, row)
      //显示编辑菜单
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        this.editLoading = false;
      })
    },
    //保存表单数据
    saveFormData() {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false;
        }
        this.editLoading = true;
        //【API请求】----保存数据
        this.$api.saveCUserCert(this.dataForm).then(() => {
          this.editLoading = false;//关闭loading框
          this.dialogFormVisible = false;//关闭表单页面
          this.initDataForm();//重置表单数据
          this.getList();//重新获取表格数据
          this.$notify({ title: '成功',  message: '保存成功', type: 'success', duration: 2000 })
        })
      })
    },
    //【按钮点击】---删除行
    handleDelete(row) {
      this.$confirm('确认删除该记录吗？', '提示', {}).then(() => {
        //【API请求】---- 删除数据
        this.$api.deleteCUserCert({ids:row.id}).then(() => {
          this.$message({  message: '操作成功', type: 'success' })
            this.pageRequest.pageNum = 1
          this.getList();
        })
      }).catch(() => {
        this.$message({  message: '操作失败', type: 'error' })
      });
    },
    //初始化表单数据，重新渲染
    initDataForm(){
      this.dataForm = {
        userId: '' ,
        applyStatus: '' ,
        createTime: '' ,
        certId: '' ,
        certPath: '' ,
        certImg: '' ,
        certName: '' ,
        id: '' ,
        certNumber: '' ,
        remark: '' ,
        userName:'',
        userPhone:'',
      };
    },
    //关闭表单弹出框
    closeDialog(){
      this.$refs['dataForm'].resetFields();
      this.dialogFormVisible = false
    },

    //详情
    handleInfo(row){
      this.dataForm = Object.assign({}, row)
      this.dialogLoading = true
      this.showDialog= true
      this.$api.getUserExamInfo({userId:this.dataForm.userId , type:this.type}).then(
          res=>{
            console.log(res,"res")
            this.itemDataForm = res.data
            console.log(this.itemDataForm , "itemDataForm")
            this.dialogLoading=false
          }
      )


    },

    closeShowDialog(){
      this.$refs['itemRuleForm'].resetFields();
      this.$refs['itemDataForm'].resetFields();
      this.showDialog = false
    },

    handlePass(row){
      this.dataForm = row
      this.dataForm.applyStatus=2
      this.$api.saveCUserCert(this.dataForm).then(() => {
        this.getList();//重新获取表格数据
        this.$notify({ title: '成功',  message: '保存成功', type: 'success', duration: 2000 })
      }).catch(res=>{
        console.log(1111)
        this.dataForm.applyStatus=1
        this.getList();//重新获取表格数据
      })
    },

    handleNoPass(row){
      this.dataForm = row
      this.dataForm.applyStatus=3
      this.$api.saveCUserCert(this.dataForm).then(() => {
        this.getList();//重新获取表格数据
        this.$notify({ title: '成功',  message: '保存成功', type: 'success', duration: 2000 })
      })
    },

    handleResult(row){
      this.dataForm = row
      this.$api.resultCUserCert(this.dataForm).then(res=>{
        this.getList();//重新获取表格数据
        this.$notify({ title: '成功',  message: '保存成功', type: 'success', duration: 2000 })
      })
    },
    handleSelect( value ){
      // console.log(value ,'value')
      if(value){
        this.searchParam.SEARCH_GE_create_time = value[0]
        this.searchParam.SEARCH_LE_create_time = value[1]
      }else{
        this.searchParam.SEARCH_GE_create_time = ''
        this.searchParam.SEARCH_LE_create_time = ''
      }
      this.getList();
    },

    clickImg(value){
        this.dialogImageUrl = value;
        this.clickImgDialog = true;
    },

    handleSelectionChange(row){
        this.multipleSelection = row.map(row => row.id);
        console.log(this.multipleSelection,"22222")
    },

    //无章证书发放




  }


}
</script>